<!-- templates/aStar.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>A* 迷宫求解器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f4f4f4;
        }
        #buttons-container {
            margin-bottom: 20px;
            text-align: center;
        }
        button, select {
            padding: 10px;
            margin: 5px;
            border: none;
            background-color: #007BFF;
            color: white;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover, select:hover {
            background-color: #0056b3;
        }
        #map-container, #info-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        #map-container {
            margin-right: 20px;
        }
        #info-container {
            width: 400px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #007BFF;
            color: white;
        }
        canvas {
            border: 1px solid #ddd;
        }
        .container {
            display: flex;
            justify-content: space-between;
            width: 90%;
            max-width: 1200px; /* 限制最大宽度 */
        }
    </style>
</head>
<body>
    <div class="container">
        <div id="map-container">
            <canvas id="mazeCanvas" width="500" height="500"></canvas>
        </div>

        <div id="info-container">
            <div id="buttons-container">
                <button onclick="randomizeMap()">重新随机化迷宫地图</button>
                <button onclick="resetPoint()">清除起点和终点</button>
                <select id="heuristic-select" onchange="setHeuristic(this.value)">
                    <option value="manhattan">曼哈顿启发函数</option>
                    <option value="euclidean">欧几里得启发函数</option>
                    <option value="chebyshev">切比雪夫启发函数</option>
                </select>
                <button onclick="startPathFinding()">开始寻路</button>
            </div>
            <table id="results-table">
                <thead>
                    <tr>
                        <th>最短路径长度</th>
                        <th>扩展节点数</th>
                        <th>生成节点数</th>
                        <th>算法计算次数</th>
                        <th>启发函数名称</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 动态添加记录 -->
                </tbody>
            </table>
            <button onclick="clearRecords()">清除记录</button>
        </div>
    </div>

    <script>

        function randomizeMap() {
            fetch('/aStar/randomize-map/')  // 确保 URL 正确，注意结尾的斜杠
            .then(response => response.json())
            .then(data => {
                maze = data.maze;
                startPoint = null;
                endPoint = null;
                drawMaze(maze);
            }).catch(error => console.error('Error:', error));
        }


        function setHeuristic(type) {
            fetch(`/aStar/set-heuristic/?type=${type}`)
            .then(response => response.json())
            .then(data => {
                console.log('Heuristic set to:', data.heuristic);
            }).catch(error => console.error('Error setting heuristic:', error));
        }

        let maze = [];
        let startPoint = null;
        let endPoint = null;
        const canvas = document.getElementById('mazeCanvas');
        const ctx = canvas.getContext('2d');
        let cellSize = 20; // 迷宫大小，后面根据返回的结果进行更改
        function resetPoint(){
            drawPoint(startPoint.x, startPoint.y, 'white');
            drawPoint(endPoint.x, endPoint.y, 'white');
            startPoint = null;
            endPoint = null;
        }
        function drawMaze(maze) {
            const canvas = document.getElementById('mazeCanvas');
            const ctx = canvas.getContext('2d');
            const numRows = maze.length;
            const numCols = maze[0].length;
            cellSize = Math.min(canvas.width / numCols, canvas.height / numRows);  // 根据迷宫大小动态计算格子大小
            ctx.clearRect(0, 0, canvas.width, canvas.height);  // 清除画布
            maze.forEach((row, y) => {
                row.forEach((cell, x) => {
                    ctx.fillStyle = cell === 1 ? 'black' : 'white';
                    ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
                });
            });
        }

        canvas.onclick = function(event) {
            const rect = canvas.getBoundingClientRect();
            const x = Math.floor((event.clientX - rect.left) / cellSize);
            const y = Math.floor((event.clientY - rect.top) / cellSize);

            if (!startPoint) {
                startPoint = {x, y};
                drawPoint(x, y, 'green');  // 起点
            } else if (!endPoint) {
                endPoint = {x, y};
                drawPoint(x, y, 'red');  // 终点
            }
        };

        function drawPoint(x, y, color) {
            const ctx = canvas.getContext('2d');
            ctx.fillStyle = color;
            ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
        }

       function addRecord(data) {

            const table = document.getElementById('results-table').getElementsByTagName('tbody')[0];
            const row = table.insertRow();
            row.insertCell(0).innerText = data.path_length;
            row.insertCell(1).innerText = data.expanded_nodes;
            row.insertCell(2).innerText = data.generated_nodes;
            row.insertCell(3).innerText = data.count;
            row.insertCell(4).innerText = document.getElementById('heuristic-select').value;
        }

        function clearRecords() {
            const table = document.getElementById('results-table').getElementsByTagName('tbody')[0];
            table.innerHTML = '';  // 清空表格内容
        }

        function startPathFinding() {
            console.log("startPathFinding...")
            drawMaze(maze);  // 重新绘制迷宫，清除旧路径
            drawPoint(startPoint.x, startPoint.y, 'green');
            drawPoint(endPoint.x, endPoint.y, 'red');
            fetch('/aStar/start-path-finding', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({startPoint, endPoint, maze})
            })
            .then(response => response.json())
            .then(data => {
                data = data.res;
                drawPath(data.path);
                addRecord(data);
            }).catch(error => console.error('Error:', error));
        }


        function drawPath(path) {
            if (Array.isArray(path)) {
                path.forEach(p => {
                    ctx.fillStyle = 'blue';
                    ctx.fillRect(p.x * cellSize, p.y * cellSize, cellSize, cellSize);
                });
            } else {
                console.error('Expected path to be an array, but received:', path);
            }
        }


    </script>
</body>
</html>
